﻿    //This program is free software: you can redistribute it and/or modify
    //it under the terms of the GNU General Public License as published by
    //the Free Software Foundation, either version 3 of the License, or
    //(at your option) any later version.

    //This program is distributed in the hope that it will be useful,
    //but WITHOUT ANY WARRANTY; without even the implied warranty of
    //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    //GNU General Public License for more details.

    //You should have received a copy of the GNU General Public License
    //along with this program.  If not, see <http://www.gnu.org/licenses/>.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.IO;
using Novacode;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        //push test

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            label0.MaxHeight = 150;
            openButton.Focus();
        }

        List<string> wordList = new List<string>();
        List<string> wordPageList = new List<string>();

        //openbutton
        private void openButton_Click(object sender, RoutedEventArgs e)
        {
            i = 0;
            
            wordPageList.Clear();
            if(dispatcherTimer != null && dispatcherTimer.IsEnabled == true)
            {
                dispatcherTimer.Stop();
            }
            if (PagesComboBox.Items.IsEmpty == false)
            {
                PagesComboBox.Items.Clear();
            }
            wordList.Clear();
            Microsoft.Win32.OpenFileDialog openfd = new Microsoft.Win32.OpenFileDialog();
            openfd.Filter = "PDF | *.pdf| Text | *.txt| MS Word|*.docx| All | *.*";
            var result = openfd.ShowDialog();
            if(result == true)
            {                
                if (openfd.FilterIndex == 2)
                {
                    textFile(openfd.FileName);
                }
                else if (openfd.FilterIndex == 3)
                {
                    //get text from docx
                    docxfile(openfd.FileName);
                }
                else
                {
                    try
                    {
                        var s = getText(openfd.FileName);
                        string[] dd = s.ToString().Split(' ', '.', ',', '\n', '\r');
                        wordList = dd.ToList();
                    }
                    catch
                    {
                        //do nothing / prompt some message
                    }
                }
            }
            openedfilelabel.Content = openfd.FileName;
            Start.Focus();
        }

        private void textFile(string file_path)
        {
            wordList.Clear();
            StreamReader sr = new StreamReader(file_path);

            string s = sr.ReadToEnd();
            sr.Close();

            string[] dd = s.Split(' ', '.', ',', '\n', '\r');
            wordList = dd.ToList();
        }


        private void docxfile(string file_path)
        {
            DocX document = DocX.Load(file_path);
            string docxText = document.Text;
            wordList = docxText.Split(' ', '.', ',', '\n', '\r').ToList();
        }
        
        private StringBuilder getText(string file_path)
        {
            StringBuilder text = new StringBuilder();
            PdfReader pdfreader = new PdfReader(file_path);

            PagesComboBox.Items.Clear();

            for (int i = 1; i <= pdfreader.NumberOfPages; i++)
            {
                text.Append(PdfTextExtractor.GetTextFromPage(pdfreader, i));
                var s = PdfTextExtractor.GetTextFromPage(pdfreader, i);
                wordPageList.Add(s);
                PagesComboBox.Items.Add(i);
            }

            

            return text;
        }
        System.Windows.Threading.DispatcherTimer dispatcherTimer;
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            if(dispatcherTimer == null || dispatcherTimer.IsEnabled == false)
            {
                dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
                dispatcherTimer.Tick += dispatcherTimer_Tick;
                dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)(1010 - SpeedSlider.Value));
                dispatcherTimer.Start();
                Stop.Focus();
            }
            else
            {
                //MessageBox.Show("the timer is running");
            }
        }

        int i = 0;
        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            if (wordList.Count > 0)
            {
                RedLetter rl = new RedLetter();
                var index = rl.SyllableCount(wordList[i]);

                wordList.RemoveAll(item => item == "");
                wordList.RemoveAll(item => item == ".");


                if (wordList[i].Length > 2)
                {
                    label0.Content = stringProcessing(wordList[i], index);

                    if (wordList[i].Length > 4)                    
                    {
                        dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)SpeedSlider.Value + 200);
                    }
                }

                if (wordList[i].Length == 2)
                {
                    dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, (int)SpeedSlider.Value);

                    label0.Content = stringProcessing(wordList[i], index);
                }

                if (wordList[i].Length == 1)
                {
                    label0.Content = null;
                }
                i++;
                if (i == wordList.Count)
                {
                    dispatcherTimer.Stop();
                    i = 0;
                }
            }
            else
            {
                dispatcherTimer.Stop();
                MessageBox.Show("no text");
            }
        }

        private void Stop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                dispatcherTimer.Stop();
                Start.Focus();
            }
            catch
            {
            }
        }

        private void fontComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            label0.FontFamily = (FontFamily)fontComboBox.SelectedItem;
        }

        private void FontSizeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            label0.FontSize = FontSizeSlider.Value;
            fontsizelabel.Content = label0.FontSize.ToString(".00");
        }

        private void fontComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            fontComboBox.SelectedIndex = 0;
            label0.FontFamily = (FontFamily)fontComboBox.SelectedItem;
        }

        private void FontSizeSlider_Loaded(object sender, RoutedEventArgs e)
        {
            FontSizeSlider.Maximum = 100;
            FontSizeSlider.Minimum = 4;
            FontSizeSlider.Width = 100;
            FontSizeSlider.Value = 20;
            FontSizeSlider.IsSnapToTickEnabled = true;
            FontSizeSlider.TickFrequency = 1;
            label0.FontSize = 20;
        }

        private void SpeedSlider_Loaded(object sender, RoutedEventArgs e)
        {
            SpeedSlider.Minimum = 10;
            SpeedSlider.Maximum = 1000;
            SpeedSlider.Value = 500;
            SpeedSlider.IsSnapToTickEnabled = true;
            SpeedSlider.TickFrequency = 50;
        }

        private void SpeedSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            try
            {
                speedlabel.Content = SpeedSlider.Value.ToString(".00");
                dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 1010 - (int)SpeedSlider.Value);
                
            }
            catch
            { }
        }

        private void ClearMemory_Click(object sender, RoutedEventArgs e)
        {
            i = 0;
            wordList.Clear();
            wordPageList.Clear();
            PagesComboBox.Items.Clear();
            label0.Content = null;
        }

        private void textbox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (wordList.Count > 0)
                {
                    var result = MessageBox.Show("would you like to read the pasted text instead?");
                    if (result == MessageBoxResult.OK)//read the pasted text
                    {
                        //clear the words
                        wordList.Clear();

                        //clear the count
                        i = 0;

                        //get the new word list from the textblock
                        string[] dd = textbox1.Text.ToString().Split(' ', '.', ',', '\n', '\r');
                        wordList = dd.ToList();
                    }
                    else
                    {
                        //do nothing
                    }
                }
                else
                {
                    string[] dd = textbox1.Text.ToString().Split(' ', '.', ',', '\n', '\r');
                    wordList = dd.ToList();
                }
            }
        }

        private void PagesComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            PagesComboBox.SelectedIndex = 0;
        }

        private void PagesComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (wordPageList.Count > 0)
            {
                i = 0;
                if (dispatcherTimer != null && dispatcherTimer.IsEnabled)
                {
                    dispatcherTimer.Stop();
                }

                wordList.Clear();
                string[] dd = wordPageList[PagesComboBox.SelectedIndex].ToString().Split(' ', '.', ',', '\n', '\r');
                wordList = dd.ToList();
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Window w = new Window();

            Label l = new Label();
            l.Content = "openPDFspeedreader\nCopyright (c) 2014 Rhett Valda \nunder GNU GPL v3 license \nI am not very certain about the legal issues. Please feel free to contact me to comment/suggest\non these terms as well as features at valdarhett@gmail.com";
            StackPanel s = new StackPanel();
            s.Children.Add(l);
            w.Title = "About";

            BitmapImage bmp = new BitmapImage(new Uri("pack://application:,,,/icon.ico"));
            w.Icon = bmp;
            w.SizeToContent = System.Windows.SizeToContent.WidthAndHeight;

            w.Content = s;            
            w.Show();
        }

        private void countSyllableButton_Click(object sender, RoutedEventArgs e)
        {
            RedLetter rl = new RedLetter();
            var i = rl.SyllableCount(textbox1.Text);
            MessageBox.Show(i.ToString());
        }

        private string stringProcessing(string word, int index)
        {
            char[] tempCharArrary = new char[100];

            for (int i = 0 ; i < tempCharArrary.Length; i++)
            {
                //lynn test ' ' => '-'
                tempCharArrary[i] = ' ';
            }

            int startingIndex = 50 - index;

            for (int i = 0; i < word.Length; i++)
            {
                tempCharArrary[i+startingIndex] = word[i];
            }

            return new string(tempCharArrary);
        }
        private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
        {
        }

    }
}
